﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Security.Cryptography;

namespace com.tiyma.common
{
    public class SystemUtil
    {
        /// <summary>
        /// 生成Md5签名
        /// </summary>
        /// <param name="srcText"></param>
        /// <returns></returns>
        public static string MD5Mac(string srcText)
        {


            MD5 myMD5 = new MD5CryptoServiceProvider();
            byte[] HashCode;
            HashCode = Encoding.Default.GetBytes(srcText);
            HashCode = myMD5.ComputeHash(HashCode);

            StringBuilder EnText = new StringBuilder();
            foreach (byte Byte in HashCode)
            {
                EnText.AppendFormat("{0:x2}", Byte);
            }

            return EnText.ToString().ToUpper();
        }

        /// <summary>
        /// 判断是否是相同的章节
        /// </summary>
        /// <param name="i_chapter_source"></param>
        /// <param name="i_chapter_target"></param>
        /// <returns></returns>
        public static bool CompareChapterName(string i_chapter_source, string i_chapter_target)
        {
            if (string.IsNullOrEmpty(i_chapter_source) || string.IsNullOrEmpty(i_chapter_target))
                return false;
            if (i_chapter_source.Equals(i_chapter_target))
                return true;

            //去掉空格
            i_chapter_source = Regex.Replace(i_chapter_source, "\\s", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            i_chapter_source = Regex.Replace(i_chapter_source, "[【】（）a-zA-Z，！？(),!?;\\.；、……]", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            i_chapter_target = Regex.Replace(i_chapter_target, "\\s", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            i_chapter_target = Regex.Replace(i_chapter_target, "[【】（）a-zA-Z，！？(),!?;；\\.、……]", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);

            if (i_chapter_source.IndexOf(i_chapter_target) > -1 || i_chapter_target.IndexOf(i_chapter_source) > -1)
                return true;

            return false;
        }

        /// <summary>
        /// 过滤内容非法字符
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public static string MSGFilterImport(string message)
        {
            if (!string.IsNullOrEmpty(message))
            {
                message = Regex.Replace(message, "select", "ＳＥＬＥＣＴ", RegexOptions.IgnoreCase);
                message = Regex.Replace(message, "insert", "ＩＮＳＥＲＴ", RegexOptions.IgnoreCase);
                message = Regex.Replace(message, "delete", "ＤＥＬＥＴＥ", RegexOptions.IgnoreCase);
                message = Regex.Replace(message, "iframe", "ＩＦＲＡＭＥ", RegexOptions.IgnoreCase);
                message = Regex.Replace(message, "update", "ＵＰＤＡＴＥ", RegexOptions.IgnoreCase);
                message = Regex.Replace(message, "script", "ＳＣＲＩＰＴ", RegexOptions.IgnoreCase);
                message = Regex.Replace(message, "truncate", "ｔｒｕｎｃａｔｅ", RegexOptions.IgnoreCase);
                message = Regex.Replace(message, "exec", "ｅｘｅｃ", RegexOptions.IgnoreCase);
                message = Regex.Replace(message, "ox", "ｏｘ", RegexOptions.IgnoreCase);
                message = Regex.Replace(message, "declare", "ｄｅｃｌａｒｅ", RegexOptions.IgnoreCase);
                message = Regex.Replace(message, "'", "‘", RegexOptions.IgnoreCase);
                message = Regex.Replace(message, "=", "", RegexOptions.IgnoreCase);
                message = Regex.Replace(message, "create", "", RegexOptions.IgnoreCase);
                message = Regex.Replace(message, "char", "", RegexOptions.IgnoreCase);
                message = Regex.Replace(message, "and", "", RegexOptions.IgnoreCase);
                message = Regex.Replace(message, "or", "", RegexOptions.IgnoreCase);
                message = Regex.Replace(message, "20%", "", RegexOptions.IgnoreCase);
                message = Regex.Replace(message, "mid", "", RegexOptions.IgnoreCase);
                message = Regex.Replace(message, "count", "", RegexOptions.IgnoreCase);
            }
            return message;
        }

        public static string SquidForwardIp
        {
            get
            {
                //string netSCalerIp=  HttpContext.Current.Request.ServerVariables["HTTP_CLIENT_IP"];
                //if (!string.IsNullOrEmpty(netSCalerIp))
                //    return netSCalerIp;

                string forwordList = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                if (string.IsNullOrEmpty(forwordList))
                    return string.Empty;

                string[] ipList = forwordList.Split(new char[] { ',' });
                if (ipList.Length >= 2 && !ipList[0].Equals("unknown"))
                {
                    return ipList[0];
                }
                else if (ipList.Length >= 2 && !ipList[1].Equals("unknown"))
                {
                    return ipList[1];
                }
                else if (ipList.Length == 1 && !ipList[0].Equals("unknown"))
                {
                    return ipList[0];
                }
                else if (!forwordList.StartsWith("10.") && !forwordList.StartsWith("unknown"))
                {
                    return forwordList;
                }
                else
                {
                    return string.Empty;
                }
            }
        }

        /// <summary>
        /// 获取用户真实的ip
        /// </summary>
        public static string UserTrueIp
        {
            get
            {
                if (HttpContext.Current != null && HttpContext.Current.Request != null)
                {
                    if (!string.IsNullOrEmpty(SquidForwardIp)) return SquidForwardIp.Trim();

                    string trueIp = HttpContext.Current.Request.ServerVariables["HTTP_CLIENT_IP"];
                    if (string.IsNullOrEmpty(trueIp))
                        trueIp = HttpContext.Current.Request.UserHostAddress;

                    return trueIp.Trim();
                }
                else
                    return string.Empty;
            }
        }

        /// <summary>
        /// 截取字符串长度
        /// </summary>
        /// <param name="i_text"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static String GetGBString(string i_text, int length)
        {
            if (string.IsNullOrEmpty(i_text))
                return i_text;
            i_text = Regex.Replace(i_text, "<[^<>]*?>", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
           
            byte[] bytes = System.Text.Encoding.Unicode.GetBytes(i_text);
            if (bytes.Length <= length)
                return i_text;

            int n = 0;　//　表示当前的字节数
            int i = 0;　//　要截取的字节数
            for (; i < bytes.GetLength(0) && n < length; i++)
            {
                //　偶数位置，如0、2、4等，为UCS2编码中两个字节的第一个字节
                if (i % 2 == 0)
                {
                    n++;　　　//　在UCS2第一个字节时n加1
                }
                else
                {
                    //　当UCS2编码的第二个字节大于0时，该UCS2字符为汉字，一个汉字算两个字节
                    if (bytes[i] > 0)
                    {
                        n++;
                    }
                }
            }
            //　如果i为奇数时，处理成偶数
            if (i % 2 == 1)
            {
                //　该UCS2字符是汉字时，去掉这个截一半的汉字
                if (bytes[i] > 0)
                    i = i - 1;
                //　该UCS2字符是字母或数字，则保留该字符
                else
                    i = i + 1;
            }
            return System.Text.Encoding.Unicode.GetString(bytes, 0, i);
        }

        public static string FilterTitle(string i_title)
        {
            if (string.IsNullOrEmpty(i_title))
                return i_title;
            //i_title = ChangeChapterName(i_title);
            //过滤字母和数字
            i_title = Regex.Replace(i_title, "<a.*?>.*?</a>", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            i_title = Regex.Replace(i_title, "<.*?tr.*?>", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            return i_title;
        }

        /// <summary>
        /// 替换违禁字符
        /// </summary>
        /// <param name="filterstr"></param>
        /// <returns></returns>
        public static string FilterSpecChars(string filterstr)
        {
            string[] filterWord = { "法高", "做爱", "去死", "国民党", "新党", "民进党", "台联", "亲民党", "宋楚瑜", "李登辉", "李洪志", "连战", "蒋中正", "蒋介石", "蒋经国", "吕秀莲", "孙中山", "孙逸仙", "孙文", "中共", "共产党", "中华人民共和国", "中华民国", "台独", "党主席", "陈水扁", "江泽民", "朱镕基", "李鹏", "赵紫阳", "李瑞环", "胡锦涛", "尉健行", "李岚清", "一贯道", "法轮功", "摩门教", "干你", "屁眼", "操你", "性交", "口交", "肛交", "吹喇叭", "鸡巴", "屌", "屄", "肏", "Fag", "烂人", "仆街", "捻", "阴茎", "傻B", "江core", "阴毛", "大花B", "大血B", "Dick", "插你", "上你", "干妳", "操妳", "插妳", "上妳", "真世界", "六四", "胡锦涛", "吴邦国", "温家宝", "贾庆林", "曾庆红", "黄菊", "吴官正", "李长春", "罗干", "做爱", "作爱", "处女膜", "一丝不挂", "爽到家", "激情图片", "激情写真", "裸体写真", "裸照", "兽交", "鸡奸", "乱伦", "素人", "熟女", "幼齿", "人妻", "巨乳", "强奸", "班禅", "台湾共和国", "台湾国", "福摩沙", "台湾独立", "台独", "中华台北", "台湾地位未定", "住民自决", "达赖喇嘛", "西藏独立", "东突厥斯坦", "斯普拉特利群岛", "尖阁群岛", "北朝鲜", "穆斯林国家", "穆斯林世界", "伊斯兰原教旨主义", " 伊斯兰原教旨主义者", "文化大革命", "法轮功", "FLG", "围攻天安门", "大法弟子", "李宏志", "九评", "美国之音", "自由亚洲", "中国人权问题", "民运", "中国威胁论", "中共政治谎言", "中共的专制政权", "六四事件", "反革命暴乱", "中国青年党", "中国民主党", "中国民主联合同盟", "中国社会民主党", "中国社会民主政团同盟", "民主进步党", "台湾独立同盟", "江泽民", "胡锦涛", "陈良宇", "温家宝", "军委主席", "军委副主席", "党中央总书记", "土共", "TG", "肃反", "政治保卫局", "AB团", "反右", "右派", "政治局常委", "国家主席", "副主席", "中共中央军委主席", "中央军委副主席", "国务院总理", "人大委员长", "毛泽东", "周恩来", "朱德", "邓小平", "彭德怀", "刘伯承", "贺龙", "陈毅", "罗荣桓", "徐向前", "聂荣臻", "叶剑英", "叶挺", "杨尚昆", "李先念", "粟裕", "徐海东", "黄克诚", "陈赓", "谭政", "萧劲光", "张云逸", "罗瑞卿", "王树声", "许光达", "许继慎", "蔡申熙", "段德昌", "曾中生", "左权", "彭雪枫", "罗炳辉", "黄公略", "方志敏", "刘志丹", "林彪" };

            for (int i = 0; i < filterWord.Length; i++)
            {
                filterstr.Replace(filterWord[i], "");
            }
            return filterstr;
        }

        /// <summary>
        /// 截取小说简介
        /// </summary>
        /// <param name="i_text"></param>
        /// <param name="i_length"></param>
        /// <returns></returns>
        public static string GetSubBookDescription(string i_text,string i_hight_word, int i_length)
        {
            bool t_is_have_key_word = false;

            i_text = FilterBookDescription(i_text);

            if (i_text.IndexOf(i_hight_word) > -1)
            {
                t_is_have_key_word = true;
            }
        

            i_text= GetGBString(i_text, i_length);

            if (i_text.IndexOf(i_hight_word) > -1)
            {
                i_text = Regex.Replace(i_text, i_hight_word, string.Format("<b>{0}</b>", i_hight_word), RegexOptions.IgnoreCase | RegexOptions.Compiled);
            }
            else
            {

                if (t_is_have_key_word && i_text.IndexOf(i_hight_word) < 0)
                {
                    i_text = i_text + string.Format("<b>{0}</b>", i_hight_word);
                }
            }

            return i_text;
        }


        /// <summary>
        /// 过滤简介中的html标签
        /// </summary>
        /// <param name="i_text"></param>
        /// <returns></returns>
        public static string FilterBookDescription(string i_text)
        {
            i_text = Regex.Replace(i_text, "&nbsp;", " ", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            i_text=Regex.Replace(i_text,"[？?，,！!；;：:……。.]*?<[\\/]*?div>",",",RegexOptions.IgnoreCase|RegexOptions.Compiled);
            i_text = Regex.Replace(i_text, "[？?，,！!；;：:……。.]*?<[\\/]*?br>", ",", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            i_text = Regex.Replace(i_text, "[？?，,！!；;：:……。.]*?<[\\/]*?p>", ",", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            i_text = Regex.Replace(i_text, "<[^<>]*?>", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);

            return i_text.Trim();

        }

        /// <summary>
        /// Json特符字符过滤，参见http://www.json.org/
        /// </summary>
        /// <param name="sourceStr">要过滤的源字符串</param>
        /// <returns>返回过滤的字符串</returns>
        public static string JsonCharFilter(string i_string)
        {
            i_string = i_string.Replace("\\", "\\\\");
            i_string = i_string.Replace("\b", "\\\b");
            i_string = i_string.Replace("\t", "\\\t");
            i_string = i_string.Replace("\n", "\\\n");
            i_string = i_string.Replace("\n", "\\\n");
            i_string = i_string.Replace("\f", "\\\f");
            i_string = i_string.Replace("\r", "\\\r");
            return i_string.Replace("\"", "\\\"");
        }

        /// <summary>
        /// 返回字符串真实长度, 1个汉字长度为2
        /// </summary>
        /// <returns>字符长度</returns>
        public static int GetStringLength(string i_string)
        {
            return Encoding.Default.GetBytes(i_string).Length;
        }
        /// <summary>
        /// 改变章节显示名称
        /// </summary>
        /// <param name="i_chapter_name"></param>
        /// <returns></returns>
        public static string ChangeChapterName(string i_chapter_name)
        {
            if (string.IsNullOrEmpty(i_chapter_name))
                return i_chapter_name;
            
            string[] t_big_chinese = new string[] {"两", "零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖", "拾", "佰", "仟", "〇" };
            string[] t_small_chinese = new string[] {"两", "零", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "百", "千", "〇" };
            string[] t_number = new string[] {"2", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "十", "百", "千", "0" };

            for (int index = 0; index < t_big_chinese.Length; index++)
            {
               
                i_chapter_name = i_chapter_name.Replace(t_big_chinese[index], t_number[index]);
                i_chapter_name = i_chapter_name.Replace(t_small_chinese[index], t_number[index]);
            }

            i_chapter_name = Regex.Replace(i_chapter_name, "(\\d+)千(\\d+)百(\\d+)十(\\d+)","$1$2$3$4", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            i_chapter_name = Regex.Replace(i_chapter_name, "(\\d+)千(\\d+)百(\\d+)", "$1$2$3", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            i_chapter_name = Regex.Replace(i_chapter_name, "(\\d+)千(\\d+)十(\\d+)", "$1$2$3", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            i_chapter_name = Regex.Replace(i_chapter_name, "(\\d+)千0(\\d+)十", "$1^0$2^0", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            i_chapter_name = Regex.Replace(i_chapter_name, "(\\d+)千0(\\d+)", "$1^00$2", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            i_chapter_name = Regex.Replace(i_chapter_name, "(\\d+)千(\\d+)", "$1$2", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            i_chapter_name = Regex.Replace(i_chapter_name, "(\\d+)千", "$1^000", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            i_chapter_name = Regex.Replace(i_chapter_name, "(\\d+)百(\\d+)十(\\d+)", "$1$2$3", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            i_chapter_name = Regex.Replace(i_chapter_name, "(\\d+)百(\\d+)", "$1$2", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            i_chapter_name = Regex.Replace(i_chapter_name, "(\\d+)百", "$1^00", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            i_chapter_name = Regex.Replace(i_chapter_name, "(\\d+)十(\\d+)", "$1$2", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            i_chapter_name = Regex.Replace(i_chapter_name, "(\\d+)十", "$1^0", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            i_chapter_name = Regex.Replace(i_chapter_name, "十(\\d+)", "1$1", RegexOptions.IgnoreCase | RegexOptions.Compiled);
           
            i_chapter_name = i_chapter_name.Replace("^", "").Replace("十","10");
            return i_chapter_name;
        }

      



        /// <summary>
        /// 获取站点完整链接地址
        /// </summary>
        /// <param name="i_site_url"></param>
        /// <param name="i_part_url"></param>
        /// <returns></returns>
        public static string GetFullUrl(string i_site_url, string i_part_url)
        {
            if (i_site_url.IndexOf("#") > -1 || i_part_url.IndexOf("#") > -1)
                return string.Empty;

            if (i_part_url.IndexOf("http://") > -1)
                return i_part_url;



            if (!i_part_url.StartsWith("http") && !i_part_url.StartsWith("/"))
            {
                i_part_url = i_site_url.Substring(0, i_site_url.LastIndexOf("/") + 1) + i_part_url;
            }

            if (i_part_url.StartsWith("/"))
            {
                Uri t_url = new Uri(i_site_url);

                i_part_url = "http://" + t_url.Host + i_part_url;
            }
            return i_part_url;

        }

    }
}
